import { ipcMain, dialog } from 'electron';
import { BrowserWindow } from 'electron';
import * as path from 'path';
import { AccountService } from './services/account-service';
import { PlatformService } from './services/platform-service';
import { UploadService } from './services/upload-service';
import { AuthService } from './services/auth-service';

export function setupIpcHandlers() {
  const accountService = new AccountService();
  const platformService = new PlatformService();
  const uploadService = new UploadService();
  const authService = new AuthService();

  // 平台管理
  ipcMain.handle('get-platforms', async () => {
    return await platformService.getPlatforms();
  });

  ipcMain.handle('add-platform', async (_, platform: any) => {
    return await platformService.addPlatform(platform);
  });

  ipcMain.handle('remove-platform', async (_, platformId: string) => {
    return await platformService.removePlatform(platformId);
  });

  // 账号管理
  ipcMain.handle('get-accounts', async () => {
    return await accountService.getAccounts();
  });

  ipcMain.handle('add-account', async (_, account: any) => {
    return await accountService.addAccount(account);
  });

  ipcMain.handle('remove-account', async (_, accountId: string) => {
    return await accountService.removeAccount(accountId);
  });

  // 扫码登录
  ipcMain.handle('start-qr-login', async (_, platform: string) => {
    return await authService.startQRLogin(platform);
  });

  ipcMain.handle('get-login-status', async (_, sessionId: string) => {
    return await authService.getLoginStatus(sessionId);
  });

  // 内置浏览器登录
  ipcMain.handle('open-browser-login', async (_, platform: string) => {
    console.log(`[IPC] 收到内置浏览器登录请求，平台: ${platform}`);
    try {
      const result = await authService.openBrowserLogin(platform);
      console.log(`[IPC] 内置浏览器登录调用成功，返回结果:`, result);
      return result;
    } catch (error) {
      console.error(`[IPC] 内置浏览器登录失败:`, error);
      throw error;
    }
  });

  // 视频上传
  ipcMain.handle('upload-video', async (_, filePath: string, metadata: any) => {
    return await uploadService.uploadVideo(filePath, metadata);
  });

  ipcMain.handle('publish-video', async (_, videoId: string, platforms: any[]) => {
    return await uploadService.publishVideo(videoId, platforms);
  });

  // 选择文件
  ipcMain.handle('select-video', async () => {
    const result = await dialog.showOpenDialog({
      properties: ['openFile'],
      filters: [
        { name: 'Videos', extensions: ['mp4', 'avi', 'mov', 'mkv', 'flv'] },
      ],
    });

    if (!result.canceled && result.filePaths.length > 0) {
      return result.filePaths[0];
    }
    return null;
  });

  // 打印功能
  ipcMain.handle('print-page', async () => {
    const mainWindow = BrowserWindow.getFocusedWindow();
    if (mainWindow && mainWindow.webContents) {
      try {
        // 打印当前页面
        mainWindow.webContents.print({
          silent: false,
          printBackground: true,
          color: true,
          margins: {
            marginType: 'printableArea'
          },
          landscape: false,
          scaleFactor: 100
        }, (success, failureReason) => {
          if (!success) {
            console.error('打印失败:', failureReason);
          } else {
            console.log('打印成功');
          }
        });
        return { success: true, message: '打印对话框已打开' };
      } catch (error) {
        console.error('打印错误:', error);
        return { success: false, message: '打印失败', error: error.message };
      }
    }
    return { success: false, message: '未找到活动窗口' };
  });

  ipcMain.handle('print-to-pdf', async () => {
    const mainWindow = BrowserWindow.getFocusedWindow();
    if (mainWindow && mainWindow.webContents) {
      try {
        // 生成PDF
        const data = await mainWindow.webContents.printToPDF({
          printBackground: true,
          color: true,
          margins: {
            marginType: 'printableArea'
          },
          landscape: false,
          scaleFactor: 100
        });
        
        // 保存PDF文件
        const result = await dialog.showSaveDialog(mainWindow, {
          filters: [{ name: 'PDF Files', extensions: ['pdf'] }],
          defaultPath: `仪表盘报告_${new Date().toISOString().split('T')[0]}.pdf`
        });
        
        if (!result.canceled && result.filePath) {
          const fs = require('fs');
          fs.writeFileSync(result.filePath, data);
          console.log('PDF保存成功:', result.filePath);
          return { success: true, message: 'PDF保存成功', filePath: result.filePath };
        }
        
        return { success: false, message: '用户取消保存' };
      } catch (error) {
        console.error('生成PDF失败:', error);
        return { success: false, message: '生成PDF失败', error: error.message };
      }
    }
    return { success: false, message: '未找到活动窗口' };
  });
}
